import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Row, Col, Icon, Menu, Dropdown, Button, Tabs } from 'antd';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { getTimeDistance } from '@/utils/utils';
import styles from './Analysis.less';
import PageLoading from '@/components/PageLoading';
import CockpitLayout from './CockpitLayout';

const { TabPane } = Tabs;

const IntroduceRow = React.lazy(() => import('./IntroduceRow'));
const SalesMap = React.lazy(() => import('./SalesMap'));
const SalesRanking = React.lazy(() => import('./SalesRanking'));
const SalesCard = React.lazy(() => import('./SalesCard'));
const TopSearch = React.lazy(() => import('./TopSearch'));
const ProportionSales = React.lazy(() => import('./ProportionSales'));
const OfflineData = React.lazy(() => import('./OfflineData'));

@connect(({ chart, dashboard, loading }) => ({
  chart,
  customers: dashboard.customers,
  balances: dashboard.balances,
  receipt: dashboard.receipt,
  cargoVolumes: dashboard.cargoVolumes,
  loading: loading.effects['chart/fetch'],
}))
class Analysis extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      salesType: 'all',
      currentTabKey: '',
      rangePickerValue: getTimeDistance('year'),
    };
    this.refreshInterval = 1000 * 40;
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.fetchIntroduceInfo();
    this.timer = setInterval(() => {
      this.fetchIntroduceInfo();
    }, this.refreshInterval);
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'chart/fetch',
      });
    });
    setTimeout(() => {
      this.setState({
        loading: false,
      });
    }, 2000);
  }

  fetchIntroduceInfo = (isFlush = true) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dashboard/fetchCustomer',
      payload: {
        queryParams: {
          isFlush,
        },
      },
    });
    dispatch({
      type: 'dashboard/fetchReceipt',
      payload: {
        queryParams: {
          isFlush,
        },
      },
    });
    dispatch({
      type: 'dashboard/fetchBalance',
      payload: {
        queryParams: {
          isFlush,
        },
      },
    });
    dispatch({
      type: 'dashboard/fetchCargoVolume',
      payload: {
        queryParams: {
          isFlush,
        },
      },
    });
  };

  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
    const { dispatch } = this.props;
    dispatch({
      type: 'chart/clear',
    });
    cancelAnimationFrame(this.reqRef);
  }

  handleChangeSalesType = e => {
    this.setState({
      salesType: e.target.value,
    });
  };

  handleTabChange = key => {
    this.setState({
      currentTabKey: key,
    });
  };

  handleRangePickerChange = rangePickerValue => {
    const { dispatch } = this.props;
    this.setState({
      rangePickerValue,
    });

    dispatch({
      type: 'chart/fetchSalesData',
    });
  };

  selectDate = type => {
    const { dispatch } = this.props;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    });
    dispatch({
      type: 'chart/fetchSalesData',
    });
  };

  isActive = type => {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return '';
    }
    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return styles.currentDate;
    }
    return '';
  };

  renderIntroduceRow = () => {
    const { loading: stateLoading } = this.state;
    const { loading: propsLoading, customers, balances, receipt, cargoVolumes } = this.props;
    const loading = stateLoading || propsLoading;
    const visitData = {
      customers,
      balances,
      receipt,
      cargoVolumes,
    };
    return <IntroduceRow loading={loading} visitData={visitData} />;
  };

  render() {
    const { rangePickerValue, salesType, currentTabKey, loading: stateLoading } = this.state;
    const { chart, loading: propsLoading } = this.props;
    const loading = stateLoading || propsLoading;
    const {
      visitData,
      visitData2,
      salesData,
      searchData,
      offlineData,
      offlineChartData,
      salesTypeData,
      salesTypeDataOnline,
      salesTypeDataOffline,
    } = chart;
    let salesPieData;
    if (salesType === 'all') {
      salesPieData = salesTypeData;
    } else {
      salesPieData = salesType === 'online' ? salesTypeDataOnline : salesTypeDataOffline;
    }
    const menu = (
      <Menu>
        <Menu.Item>操作一</Menu.Item>
        <Menu.Item>操作二</Menu.Item>
      </Menu>
    );

    const dropdownGroup = (
      <span className={styles.iconGroup}>
        <Dropdown overlay={menu} placement="bottomRight">
          <Icon type="ellipsis" />
        </Dropdown>
      </span>
    );

    const activeKey = currentTabKey || (offlineData[0] && offlineData[0].name);
    return (
      <>
        <Tabs defaultActiveKey="1" tabBarStyle={{ padding: 0 }}>
          <TabPane tab="航线货量" key="1">
            <CockpitLayout subject={'吉祥航空物流'}>
              <Suspense fallback={null}>
                <div className={styles.salesMapBg}>
                  <Row type="flex" justify="start">
                    <Col xs={24} sm={24} md={24} lg={24} xl={17}>
                      <SalesMap loading={loading} height={700} />
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={7}>
                      <SalesRanking loading={loading} height={700} />
                    </Col>
                  </Row>
                </div>
              </Suspense>
            </CockpitLayout>
          </TabPane>
          <TabPane tab="销售统计" key="2">
            <CockpitLayout subject={'吉祥航空物流'}>
              <Suspense fallback={<PageLoading />}>{this.renderIntroduceRow()}</Suspense>
              <Suspense fallback={null}>
                <div className={styles.salesCardBg}>
                  <SalesCard
                    rangePickerValue={rangePickerValue}
                    isActive={this.isActive}
                    handleRangePickerChange={this.handleRangePickerChange}
                    loading={loading}
                    selectDate={this.selectDate}
                  />
                </div>
              </Suspense>
            </CockpitLayout>
          </TabPane>
        </Tabs>
      </>
      // <GridContent>
      //   <Suspense fallback={<PageLoading />}>{this.renderIntroduceRow()}</Suspense>
      //   <Suspense fallback={<PageLoading />}>
      //     <SalesMap />
      //   </Suspense>
      //   <Suspense fallback={null}>
      //     <SalesCard
      //       rangePickerValue={rangePickerValue}
      //       salesData={aaa}
      //       isActive={this.isActive}
      //       handleRangePickerChange={this.handleRangePickerChange}
      //       loading={loading}
      //       selectDate={this.selectDate}
      //     />
      //   </Suspense>
      //   {/* <div className={styles.twoColLayout}>
      //     <Row gutter={24} type="flex">
      //       <Col xl={12} lg={24} md={24} sm={24} xs={24}>
      //         <Suspense fallback={null}>
      //           <TopSearch
      //             loading={loading}
      //             visitData2={visitData2}
      //             selectDate={this.selectDate}
      //             searchData={searchData}
      //             dropdownGroup={dropdownGroup}
      //           />
      //         </Suspense>
      //       </Col>
      //       <Col xl={12} lg={24} md={24} sm={24} xs={24}>
      //         <Suspense fallback={null}>
      //           <ProportionSales
      //             dropdownGroup={dropdownGroup}
      //             salesType={salesType}
      //             loading={loading}
      //             salesPieData={salesPieData}
      //             handleChangeSalesType={this.handleChangeSalesType}
      //           />
      //         </Suspense>
      //       </Col>
      //     </Row>
      //   </div>
      //   <Suspense fallback={null}>
      //     <OfflineData
      //       activeKey={activeKey}
      //       loading={loading}
      //       offlineData={offlineData}
      //       offlineChartData={offlineChartData}
      //       handleTabChange={this.handleTabChange}
      //     />
      //   </Suspense> */}
      // </GridContent>
    );
  }
}

export default Analysis;
